/**
 * 加入收藏
 */
function doAddFavorite() {
	$.ajax({
		type : 'POST',
		url : rootPath + "/home/isLogin",
		async : true,
		dataType : 'json',
		success : function(json) {
			if (json.code == '1') {
				//已登录，可以收藏
				var productId = $("#productId").val();
				$.ajax({
					type : "post",
					url : rootPath + '/wx/favorite/addFavorite',
					data : {
						productId : productId
					},
					datatype : "json",
					success : function(data) {
						if (data.code == '1') {
							var favoriteId = data.data;
							layer.msg(data.msg, {
								time : 3000
							});
							$("#scLink").removeAttr('onclick');
							$("#scLink").attr("onclick", "doDelFavorite('" + favoriteId + "');");
							$("#scLi").removeClass('icon1');
							$("#scLi").addClass('iconsc');
							$("#scEmTxt").html('取消收藏');
						} else {
							layer.msg(data.msg, {
								time : 3000
							});
						}
					},
					error : function() {
						layer.msg('暂时无法加入收藏', {
							time : 1000
						});
					}
				});
			} else {
				// layer.msg('请先登录！',{time:1000});
				window.location.href = rootPath + '/home/loginPage';
			}
		}
	});
}
/**
 * 取消收藏
 */
function doDelFavorite(favoriteId) {
	$.ajax({
		type : "post",
		url : rootPath + '/wx/favorite/doDelFavorite',
		data : {
			idArrStr : favoriteId
		},
		datatype : "json",
		success : function(json) {
			if (json.code == '1') {
				layer.msg(json.msg, {
					time : 3000
				});
				$("#scLink").removeAttr('onclick');
				$("#scLink").attr("onclick", "doAddFavorite();");
				$("#scLi").removeClass('iconsc');
				$("#scLi").addClass('icon1');
				$("#scEmTxt").html('收藏');
			} else {
				layer.msg(json.msg, {
					time : 3000
				});
			}
		},
		error : function() {
			layer.msg('暂时无法取消收藏', {
				time : 1000
			});
		}
	});
}
/**
 * 初始化
 */
$(function() {
	$('#myloginbox .hd span a').click(function() {
		$('#myloginbox').toggle();
	});

	/**
	 * 键盘点击事件，回车键，执行搜索
	 */
	$(".myloginbox input").bind('keypress', function(event) {
		if (event.keyCode == "13") {
			doLogin();
		}
	});

	// 初始化选中所有规格项第一个
	var market_product_price = parseFloat($("#market_product_price").val());
	var base_product_price = parseFloat($("#base_product_price").val());
	var total_spec_price = 0;
	var choseSpecLiArr = $(".xsq_part li.selected");
	if (choseSpecLiArr) {
		$.each(choseSpecLiArr, function(i, item) {
			try {
				var specPrice = item.getAttribute('spec_price');
				total_spec_price += parseFloat(specPrice);
			} catch (e) {
				console.log(e);
			}
		});
	}

	// $("#total_product_market_price").text("￥" + (market_product_price + total_spec_price));
	// $("#total_product_price").text(base_product_price + total_spec_price);

	// 登录窗口
	jQuery('.login_nav ul li').click(function() {
		TabSelect(".login_nav ul li", "div.login_part11", "current", jQuery(this))
	});

	jQuery('.login_nav ul li').eq(0).trigger("mouseover");
	$('#myloginbox .hd span a').click(function() {
		$('#myloginbox').toggle();
		$('#myloginbox').css("display", "none");
	});

	// 单击台式机>联想M450 根据类型进行查询
	$("a[categoryId]").each(function() {
		$(this).click(function() {
			var categoryId = $(this).attr("categoryId");
			$("#category_id").val(categoryId);
			$("#product_search_form").submit();
		});
	});

	$("#carousel_photo_container").jqueryzoom({
		xzoom : 540, //放大图的宽度(默认是 200)
		yzoom : 540, //放大图的高度(默认是 200)
		offset : 1, //离原图的距离(默认是 10)
		position : "center", //放大图的定位(默认是 "right")
		preload : 1
	});
	$('a.backtop').click(function() {
		$('body,html').animate({
			scrollTop : 0
		}, 1000);
	});

	// 规格项单击事件
	$('.xsq_part ul li a').click(function() {
		$(this).parent().toggleClass('selected');
		$(this).parent().siblings().removeClass('selected');
		changePrice();
	});

	// 规格项变动影响商品总价格
	function changePrice() {
		var market_product_price = parseFloat($("#market_product_price").val());
		var base_product_price = parseFloat($("#base_product_price").val());

		var total_spec_price = 0;
		$("dt[name='spec_list']").each(function() {
			var spec_id = $(this).attr("spec_id");
			var spec_name = $(this).find("strong").text();
			var select_li = $(this).find("ul").find("li.selected");
			var spec_price = select_li.attr('spec_price');
			if (spec_price != undefined) {
				total_spec_price = total_spec_price + parseFloat(spec_price);
			}
		});
		$("#total_product_market_price").text("￥" + (market_product_price + total_spec_price));
		$("#total_product_price").text(base_product_price + total_spec_price);
	}

	jQuery('.product_nav ul li').click(function() {
		TabSelect(".product_nav ul li", "div.prd_con", "current", jQuery(this))
	});
	jQuery('.product_nav ul li').eq(0).trigger("click");
	$('.comment_piclist dl dt img').click(function() {
		$(this).parent().toggleClass('current');
		$(this).parent().siblings('dt').removeClass('current');
		if ($(this).parent().attr("class") == "current") {
			var mysrc = $(this).attr('src').split("?")[0];
			$(this).parent().parent().parent().parent().find('.bigpics img').attr('src', mysrc);
			$(this).parent().parent().parent().parent().find('.bigpics').show();
		} else {
			$(this).parent().parent().parent().parent().find('.bigpics').hide();
		}
	});
	$('.icon_jia').click(function() {
		var t = $(this).parent().find('input').val();
		if (t < 1000) {
			t++;
			$(this).parent().find('input').val(t);
		} else {
			$(this).parent().find('input').val('1000');
		}
	});

	$('.icon_jian').click(function() {
		var t = $(this).parent().find('input').val();
		if (t > 1) {
			t--;
			$(this).parent().find('input').val(t);
		} else {
			$(this).parent().find('input').val('1');
		}
	});
	jQuery('#duice').click(function() {
		jQuery('.wthpop').show();
	})
	jQuery('.wthpop>p>span').click(function() {
		jQuery('.wthpop').hide()
	})

	//tab function
	function TabSelect(tab, con, addClass, obj) {
		var jQuery_self = obj;
		var jQuery_nav = jQuery(tab);

		jQuery_nav.removeClass(addClass), jQuery_self.addClass(addClass);

		var jQuery_index = jQuery_nav.index(jQuery_self);
		var jQuery_con = jQuery(con);
		jQuery_con.hide(), jQuery_con.eq(jQuery_index).show();
	}

	// 异步查询热门搜索关键字
	url = rootPath + "/pc/listHotSearchKey";
	$.ajax({
		type : 'POST',
		url : url,
		async : true,
		data : {},
		dataType : 'json',
		success : function(json) {
			if (json) {
				for (var i = 0; i < json.length; i++) {
					var searchKey = $("<a href='javascript:void(0)' >" + json[i].keyIntro + "</a>");
					searchKey.click(function() {
						$("#search_key").val($(this).text());
						$("#product_search_form").submit();
					});
					$("#hot_search_key_name").after(searchKey);
				}
			}
		}
	});

	// 登录
	$("#btn_login").click(function() {
		doLogin();
	});

	// 添加购物车
	$("#btn_add_shoppingcart").click(function() {
		var flag = true;
		var spec = [];
		$("dt[name='spec_list']").each(function() {
			var spec_name = $(this).find("strong").text();
			var select_li = $(this).find("ul").find("li.selected");
			var spec_id = select_li.attr("spec_id");
			var selected_num = select_li.length;
			if (selected_num == 0) {
				layer.msg('请选择' + spec_name, {
					time : 2000
				});
				flag = false;
				return false;
			} else {
				select_li.each(function() {
					spec.push({
						id : spec_id,
						specName : spec_name,
						specValue : $(this).find("a").text()
					});
				});
			}
		});
		if (!flag) {
			return false;
		}
		// 判断用户是否登录
		var url = rootPath + "/home/checkLogin";
		$.ajax({
			type : "post",
			url : url,
			data : {},
			datatype : "json",
			success : function(json) {
				if (json.resultCode == '1') {
					var buy_num = $("#buy_num").val();
					var url = rootPath + "/pc/shoppingcart/add";
					var params = {
							productId : $("#productId").val(),
							buyNum : buy_num,
							addFlag : 1,
							specListJson : JSON.stringify(spec)
					};
					$.ajax({
						type : "post",
						url : url,
						data : params,
						datatype : "json",
						success : function(json) {
							if (json.resultCode == '1') {
								layer.msg('添加购物车成功', {
									time : 2000
								});
								doGetShopCount();
							}
						},
						error : function() {
							layer.msg('添加购物车失败', {
								time : 2000
							});
						}
					});
				} else {
					// 弹出登录窗口
					$('#myloginbox').toggle();
				}
			},
			error : function() {
				layer.msg('error', {
					time : 1000
				});
			}
		});
	});

	// 添加并跳转到购物车
	$("#btn_add_to_shoppingcart").click(function() {
		var flag = true;
		var spec = [];
		$("dt[name='spec_list']").each(function() {
			var spec_name = $(this).find("strong").text();
			var select_li = $(this).find("ul").find("li.selected");
			var spec_id = select_li.attr("spec_id");
			var selected_num = select_li.length;
			if (selected_num == 0) {
				layer.msg('请选择' + spec_name, {
					time : 2000
				});
				flag = false;
				return false;
			} else {
				select_li.each(function() {
					spec.push({
						id : spec_id,
						specName : spec_name,
						specValue : $(this).find("a").text()
					});
				});
			}
		});
		if (!flag) {
			return false;
		}
		// 判断用户是否登录
		var url = rootPath + "/home/checkLogin";
		$.ajax({
			type : "post",
			url : url,
			data : {},
			datatype : "json",
			success : function(json) {
				if (json.resultCode == '1') {
					// 如果登录成功，则添加购物车，跳转到结算页面
					var url = rootPath + "/pc/shoppingcart/directAdd";
					var form = $('<form></form>');
					form.attr('action', url);
					form.attr('method', 'post');
					form.attr('target', '_self');
					form.appendTo("body");
					form.append($("<input type='hidden' name='addFlag' value='1'/>"));
					form.append($("<input type='hidden' name='buyNum' value='" + $("#buy_num").val() + "'/>"));
					form.append($("<input type='hidden' name='directBuy' value='1'/>"));
					form.append($("<input type='hidden' name='productId' value='" + $("#productId").val() + "'/>"));
					form.append($("<input type='hidden' name='specListJson' value='" + JSON.stringify(spec) + "'/>"));
					form.submit();
				} else {
					// 弹出登录窗口
					$('#myloginbox').toggle();
				}
			},
			error : function() {
				layer.msg('error', {
					time : 1000
				});
			}
		});

	});

	queryEvaluation(1);

	//分页
	//$(".page_selector").sSelect();
	$('.del_part p input,#delbox .hd span a,#delbox .bottom  p input').click(function() {
		$('#delbox').toggle();
	});
	//--------function in input text to jump into the page-------------//
	$("#btn_go_input").blur(function() {
		validateInputPageNO()
	});
	$("#btn_go").click(function() {
		validateInputPageNO();
	});

	$("#select_numPerPage").change(function() {
		var currentValue = $(this).val();
		queryEvaluation(1);
	});
});

//异步查询商品评论
function queryEvaluation(curPage) {
	var productId = $("#productId").val();
	$.ajax({
		type: 'POST',
		url: rootPath + "/pc/product/queryProductEvaluation",
		async: true,
		data: {productId : productId, tmpCurrentPage : curPage},
		dataType: 'json',
		success: function(json) {
			$("#evaluationUlList").html("");
			var liInfos = [];
			$.each(json.evaluationPage.recordList, function(i, record){
				//星级
				var star = "";
				for (var i = 0; i < 5; i++) {
					if (i < record.score) {
						star += "<img src='"+rootPath+"/statics/images/star-on.png' alt='"+(i+1)+"'>";
					} else {
						star += "<img src='"+rootPath+"/statics/images/star-off.png' alt='"+(i+1)+"'>";
					}
				}
				var li = "<li>"+
				"<div class='member_picbox'>";
				if (record.headImage != "" && record.headImage != null) {
					li += "<img src='" + imgRootURL + record.headImage+"?x-oss-process=image/resize,h_100/format,png' />";
				} else {
					li += "<img src='"+rootPath+"/statics/images/comment_pic1.jpg' />";
				}
				li += hideUserName(record.userName) + //"<h2>"+record.levelName+"</h2>"+
				"	<div class='comment_star'>"+star+"</div>"+
				"</div>"+
				"<div class='comment_mainbody'>"+
				"	<div class='comment_intro'>"+
				"		<p>"+record.content+"</p>"+
				"	</div>"+
				"	<div class='comment_piclist'>"+
				"		<dl>";
				$.each(record.filePathList, function(i2, filePath){
					li += "		<dt>"+
					"			<img src='" + imgRootURL + filePath+"?x-oss-process=image/resize,h_100/format,png' />"+
					"		</dt>";
				});
				li += "		</dl>"+
				"	</div>"+
				"	<div class='bigpics' style='height:auto; width:auto; display: none;'>"+
				"		<img style='height:auto; width:auto;' src='"+rootPath+"/statics/images/detail_pic.jpg' />"+
				"	</div>"+
				"	<div class='fl_part3'>"+
				"		<p>"+
				"			<span></span>"+record.productName + 
				"			<span></span>"+record.createTimeStr+
				"		</p>"+
				"	</div>"+
				"</div>"+
				"</li>";
				liInfos.push(li);
			});
			$("#evaluationUlList").append(liInfos.toString());
			//图片放大
			$("#evaluationUlList li dl dt img").click(function(){
				$(this).parent().toggleClass('current');
				$(this).parent().siblings('dt').removeClass('current');
				if ($(this).parent().attr("class") == "current") {
					var mysrc = $(this).attr('src').split("?")[0];
					$(this).parent().parent().parent().parent().find('.bigpics img').attr('src', mysrc+"?x-oss-process=image/resize,h_1000/format,png");
					$(this).parent().parent().parent().parent().find('.bigpics').show();
				} else {
					$(this).parent().parent().parent().parent().find('.bigpics').hide();
				}
			});
			//分页
			$("#pagination").html("");
			var startRowNum = json.evaluationPage.startRowNum;
			var endRowNum = json.evaluationPage.endRowNum;
			var currentPage = json.evaluationPage.currentPage;
			var pageCount = json.evaluationPage.pageCount;
			var totalCount = json.evaluationPage.totalCount;
			var numPerPage = json.evaluationPage.numPerPage;
			var pagination = "<div class='left'>" +
			"	<p>当前" + startRowNum + " - "+endRowNum+" 条 共计"+totalCount+" 条</p>" +
			"</div>" +
			"<div class='center'>" +
			"	<p>";
			if (currentPage == 1) {
				pagination+="<a>首页</a>" +
				"		<a>上一页</a>";
			}
			if (currentPage > 1) {
				pagination+="<a href='javascript:;' onclick='queryEvaluation(1)'>首页</a>" +
				"		<a href='javascript:;' onclick='queryEvaluation("+(currentPage-1)+")'>上一页</a>";
			}
			$.each(json.evaluationPage.pageItems,function(i,v){
				if (v == null || v == "" || v == undefined) {
					pagination+="<a href='javascript:;'>...</a>";
				}
				if (v != null && v == currentPage) {
					pagination+="<a href='javascript:;' class='current'>"+v+"</a>";
				}
				if (v != null && v != currentPage) {
					pagination+="<a href='javascript:;' onclick='queryEvaluation("+v+");'>"+v+"</a>";
				}
			});
			if (currentPage == pageCount) {
				pagination+="<a>下一页</a>" +
				"		<a>尾页</a>";
			}
			if (currentPage < pageCount) {
				pagination+="<a href='javascript:;' onclick='queryEvaluation("+(currentPage+1)+")'>下一页</a>" +
				"		<a href='javascript:;' onclick='queryEvaluation("+pageCount+")'>尾页</a>";
			}
			pagination+="	<input id='btn_go_input' type='text' class='inputstyle11' value='"+currentPage+"' placeholder='跳转页数'>";
			pagination+="	<input id='btn_go' type='button' class='inputbtn2' value='确定'>";
			pagination+="	<input type='hidden' name='numPerPage' id='select_numPerPage' value='"+numPerPage+"'>" +
			"	</p>" +
			"</div>";
			$("#pagination").append(pagination);
			$("#evaluationCount1").html("评论("+totalCount+")");
			$("#evaluationCount2").html("全部评价("+totalCount+")");
			//分页跳转事件
			$("#btn_go_input").blur(function(){
				validateInputPageNO(pageCount)
			});
			$("#btn_go").click(function(){
				validateInputPageNO(pageCount);
			});
			$("#select_numPerPage").change(function(){
				var currentValue=$(this).val();
				queryEvaluation(1);
			});
		}
	});
}
//隐藏用户名
function hideUserName(userName){
	var hideName = "";
	if (userName.length < 3) {
		hideName = userName.substr(0,1) + "***";
	} else {
		hideName = userName.substr(0,1) + "***" + userName.substr(-1,1);
	}
	return hideName;
}

//验证跳转页硕必须是数字
function validateInputPageNO(pageCount) {
	var str_page = $("#btn_go_input").val();
	if (isNaN(str_page)) {
		$("#btn_go_input").val(1);
		return;
	}
	var n = parseInt(str_page);
	if (n > pageCount) {
		n = pageCount;
	}
	queryEvaluation(n);
}

$(function() {
	doGetShopCount();
});

function doGetShopCount() {
	/**
	 * 获取购物车数量
	 */
	$.ajax({
		type : 'POST',
		url : rootPath + "/pc/shoppingcart/getShoppingcarCount",
		async : true,
		dataType : 'json',
		success : function(json) {
			if (json.code == '1') {
				$("#shopCount").html(json.data);
			}
		}
	});
}

///**
// * 一级分类下多个小分类筛选
// */
//function doProductSearch(categoryId) {
//	var categoryArr = $(".xz_part .temp_ul_" + categoryId + " input");
//	var categoryIdStr = '';
//	for (var i = 0; i < categoryArr.length; i++) {
//		if (categoryArr[i].checked) {
//			categoryIdStr += categoryArr[i].value + ",";
//		}
//	}
//	if (categoryIdStr) {
//		window.open(rootPath + "/pc/product/search?categoryId=" + categoryIdStr);
//	}
//}

/**
 * 一级分类下多个小分类筛选
 */
function doProductSearch(categoryId) {
	var brandLabelArr = $(".brand_ul .brand_ul_" + categoryId + " label.checked");
	var brandIdStr = '';
	if(brandLabelArr && brandLabelArr.length > 0) {
		for(var i = 0; i < brandLabelArr.length; i ++) {
			if(i == (brandLabelArr.length - 1)) {
				brandIdStr += brandLabelArr[i].title;
			} else {
				brandIdStr += brandLabelArr[i].title + ',';
			}
		}
	}
	
	var categoryArr = $(".xz_part .temp_ul_" + categoryId + " label.checked");
	var categoryIdStr = '';
	for (var i = 0; i < categoryArr.length; i++) {
		categoryIdStr += categoryArr[i].title + ",";
	}
	if (categoryIdStr || brandIdStr) {
		$(".xz_part .checked").removeClass('checked');
		$("input[type=button][id^='btnBrandCategorySearch_']").css('background-color', 'gray');
		window.open(rootPath + "/pc/product/search?categoryId=" + categoryIdStr + "&brandIds=" + brandIdStr);
	}
}


function doLogin() {

	$("#errorDiv").html('');
	//校验
	var userCode = $("#userCode").val();
	var password = $("#password").val();
	if ($.trim(userCode).length < 6) {
		$("#errorDiv").html('<span class="glyphicon glyphicon-minus-sign"></span>&nbsp;请输入正确的用户名！');
		$("#userCode").focus();
		$("#userCode").select();
		return;
	}
	if ($.trim(password).length < 6) {
		$("#errorDiv").html('<span class="glyphicon glyphicon-minus-sign"></span>&nbsp;请输入正确的密码！');
		$("#password").focus();
		$("#password").select();
		return;
	}
	$.ajax({
		url : rootPath + "/home/login",
		type : "post",
		async : false,
		dataType : 'json',
		data : {
			userCode : userCode,
			password : password
		},
		success : function(json) {
			if (json.code == '1') {
				$('#myloginbox').toggle();
				/**
						var spec = [];
						$("dt[name='spec_list']").each(function(){
							var spec_name= $(this).find("strong").text();
							var select_li = $(this).find("ul").find("li.selected");
							var spec_id = select_li.attr("spec_id");
							var selected_num = select_li.length;
							if(selected_num == 0){
								layer.msg('请选择'+spec_name,{time:2000});
								flag = false;
								return false;
							}else{
								select_li.each(function(){
									spec.push({id:spec_id,specName:spec_name,specValue:$(this).find("a").text()});
								});
							}
						});

						var buy_num = $("#buy_num").val();
						var url = rootPath + "/pc/shoppingcart/add";
						var params = {
							productId : $("#productId").val(),
							buyNum : buy_num,
							addFlag : 1,
							specListJson:JSON.stringify(spec)
						};
						$.ajax({
							type : "post",
							url : url,
							data : params,
							datatype : "json",
							success : function(json) {
								if (json.resultCode == '1') {
									layer.msg('添加购物车成功',{time:2000});
									doGetShopCount();
								}
							},
							error : function() {
								layer.msg('添加购物车失败',{time:2000});
							}
						});
				 */
				//  刷新当前页面
				window.location.reload(true);
			} else {
				$("#errorDiv").html('<span class="glyphicon glyphicon-minus-sign"></span>&nbsp;' + json.msg);
				$("#password").focus();
				$("#password").select();
			}
		}
	});
}
